package com.itwxz.quartz.task;

import com.itwxz.common.core.redis.RedisCache;
import com.itwxz.common.utils.MailSenderUtils;
import com.itwxz.system.domain.vo.SearchOrderVo;
import com.itwxz.system.service.IWxzOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class EveryDayTask {
	@Autowired
	private RedisCache redisCache;

	@Autowired
	private IWxzOrderService wxzOrderService;

	@Autowired
	private MailSenderUtils mailSenderUtils;

	public void clearEveryDay() {
		log.info("执行每日清理任务：{}...", LocalDateTime.now());

		//清除PC端echarts列表数据
		redisCache.deleteObject("statistics::list");
        // 排行榜数据
        redisCache.deleteObject("staff::ranking");
	}

	/**
	 *  执行发送邮件任务
	 */
	public void sendDailyMail() {
		log.info("执行发送邮件任务：{}...", LocalDateTime.now());

		List<SearchOrderVo> vos = wxzOrderService.selectOrderStatus23();
		if (vos == null || vos.isEmpty()) return;

		// 1. 按 staffId 分组
		Map<Long, List<SearchOrderVo>> grouped = vos.stream()
				.filter(vo -> vo.getStaffEmail() != null && !vo.getStaffEmail().isBlank())
				.collect(Collectors.groupingBy(SearchOrderVo::getStaffId));

		// 2. 遍历每个维修人员，合并订单信息
		for (Map.Entry<Long, List<SearchOrderVo>> entry : grouped.entrySet()) {
			List<SearchOrderVo> staffOrders = entry.getValue();
			SearchOrderVo first = staffOrders.get(0); // 同一个人的基本信息相同

			String staffEmail = first.getStaffEmail();
			String staffName = first.getStaffName();

			// 提取所有订单 ID
			String orderIds = staffOrders.stream()
					.map(vo -> String.valueOf(vo.getId()))
					.collect(Collectors.joining(", "));

			// 订单数量
			int orderCount = staffOrders.size();

			// 调用封装好的方法（这里你可以让 sendOrderReminderMail 支持多个订单）
			mailSenderUtils.sendOrderReminderMail(
					staffEmail,
					staffName,
					orderIds,
					orderCount
			);
		}
	}

}
